const express = require('express');
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
const { getUserByEmail, createUser } = require('../models/user');
const router = express.Router();

// 注册路由
router.post('/register', async (req, res) => {
  const { username, email, password } = req.body;
  console.log(req.body);

  // 检查用户是否已存在
  const existingUser = await getUserByEmail(email);
  if (existingUser) {
    return res.status(400).json({ message: '用户已存在' });
  }

  // 加密密码
  const hashedPassword = await bcrypt.hash(password, 10);

  // 创建新用户
  const newUser = {
    username,
    email,
    password: hashedPassword
  };

  let user = await createUser(newUser);
  console.log(user);
  if (!user) {
    return res.status(500).json({ message: '服务器错误' });
  } else {
    res.status(201).json({ message: '用户注册成功' });
  }
});

// 登录路由
router.post('/login', async (req, res) => {
  const { email, password } = req.body;

  console.log(email, password)
  // 查找用户
  const user = await getUserByEmail(email);
  if (!user) {
    return res.status(400).json({ message: '用户不存在' });
  }

  // 验证密码
  const isPasswordValid = await bcrypt.compare(password, user.password);
  if (!isPasswordValid) {
    return res.status(400).json({ message: '密码错误' });
  }

  // 生成 JWT
  const token = jwt.sign({ userId: user.id }, process.env.JWT_SECRET, { expiresIn: '1h' });

  res.json({ token });
});

module.exports = router; 


//{"email":"test2@qq.com","password":"test"}